from flask import request, jsonify, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from .. import db
from ..models import User
from ..utils import success_response, error_response
from . import api
from datetime import datetime

@api.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return error_response('用户名和密码不能为空', 400)
        
        # 查找用户
        user = User.query.filter_by(username=username).first()
        
        # 验证用户和密码
        if user and user.check_password(password):
            # 创建访问令牌
            access_token = create_access_token(identity=user.id)
            
            # 更新最后登录时间
            user.last_login = datetime.utcnow()
            db.session.commit()
            
            return success_response({
                'userId': user.id,
                'username': user.username,
                'role': user.role,
                'accessToken': access_token
            }, '登录成功')
        else:
            return error_response('用户名或密码错误', 401)
    except Exception as e:
        current_app.logger.error(f'登录错误: {str(e)}')
        return error_response('登录失败，请稍后重试', 500)

@api.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取用户信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return error_response('用户不存在', 404)
        
        return success_response({
            'userId': user.id,
            'username': user.username,
            'role': user.role,
            'lastLogin': user.last_login.isoformat() if user.last_login else None
        }, '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取用户信息错误: {str(e)}')
        return error_response('获取用户信息失败', 500)